﻿var manualInterfaceXMLPath = "interfaceXML/manualQQT.xml";
var automationInterfaceXMLPath = "interfaceXML/automationQQT.xml";
var DWTRXMLPath = "interfaceXML/manualDWTR.xml";
var commonInfoXMLPath = "interfaceXML/commonInfo.xml";


/***********************************
 * 基础类 
 ************************************/

var Interface = {
	createNew: function(actionCode,name,content,init,callback,regexp) {
		var interface = {};
		interface.actionCode = actionCode;
		interface.name = name;
		interface.content = content;
		interface.init = init;
		interface.callback = callback;
		interface.regexp = regexp;
		
		return interface;
	}
};

var Log = {
	createNew: function(actionCode,actionName,requestText,responseText,requestTime,elapsedTime,result) {
		var log = {};
		log.actionCode = actionCode;
		log.actionName = actionName;
		log.requestText = requestText;
		log.responseText = responseText;
		log.requestTime = requestTime;
		log.elapsedTime = elapsedTime;
		log.result = result;
		return log;
	}
};


if (typeof Result == "undefined") {
	var Result = {};
	Result.Pass = "Pass";
	Result.Fail= "Fail";
}


var RequestOption = {
	createNew: function(method,url,contentType) {
		var requestOption = {}
		requestOption.method = method;
		requestOption.url = url;
		requestOption.contentType = contentType;

		return requestOption;
	}
};



/***********************************
 * 基础函数
 ************************************/
var Timer = {
	_data: {},
	start: function(key) {
		Timer._data[key] = new Object();
		Timer._data[key].startTime = new Date();
		Timer._data[key].endTime = null;
		Timer._data[key].elapsedTime = null;
	},
	stop: function(key) {
		var time = Timer._data[key].startTime;
		if (time) {
			Timer._data[key].endTime = new Date();
			Timer._data[key].elapsedTime = Timer._data[key].endTime - time;
		}
	},
	getStartTime: function(key) {
		return Timer._data[key].startTime;
	},
	getEndTime: function(key) {
		return Timer._data[key].endTime;
	},
	getElapsedTime: function(key) {
		return Timer._data[key].elapsedTime;
	}
};

/**
 * <param name="x">待显示的日期时间，例如new Date()</param>
 * <param name="y">需要显示的格式，例如yyyy-MM-dd hh:mm:ss:SSSS</param>
 */
function date2str(x,y) {
	var z = {M:x.getMonth()+1,d:x.getDate(),H:x.getHours(),m:x.getMinutes(),s:x.getSeconds()};
	y = y.replace(/(M+|d+|H+|m+|s+)/g,function(v) {return ((v.length>1?"0":"")+eval('z.'+v.slice(-1))).slice(-2)});
	y = y.replace(/(S+)/g,function(v) {return x.getMilliseconds().toString().slice(-v.length)});
	return y.replace(/(y+)/g,function(v) {return x.getFullYear().toString().slice(-v.length)});
}

/**
 * 时间处理
 * 以yyyyMMdd的格式返回当前时间
 */
Date.prototype.yyyyMMdd = function() {
   var yyyy = this.getFullYear().toString();
   var MM = (this.getMonth()+1).toString(); // getMonth() is zero-based
   var dd  = this.getDate().toString();
   return yyyy + (MM[1]?MM:"0"+MM[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};

/**
 * 时间处理
 * 以HHmm的格式返回当前时间
 */
Date.prototype.HHmm = function() {
   var HH = this.getHours().toString();
   var mm = (this.getMinutes()).toString();
   return (HH[1]?HH:"0"+HH[0]) + (mm[1]?mm:"0"+mm[0]);  // padding
};

/**
 * 如果小于10，前面补充0
 */
function checkTime(i){
	var str = i.toString();
	return str[1]?str:"0"+str[0];
}

/**
 * Copy some content to clipboard
 */
function copyToClipboard(content) {
	if (window.clipboardData && clipboardData.setData) {
		clipboardData.setData('text', content);
	}
}


/**
 * Load XML document
 */
function loadXMLDoc(dname) {
	try {
		//Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}
	catch(e) {
		try {
			//Firefox, Mozilla, Opera, etc.
			xmlDoc=document.implementation.createDocument("","",null);
		}
		catch(e) {
			alert(e.message);
		}
	}

	try	{
		xmlDoc.async=false;
		xmlDoc.load(dname);
		return(xmlDoc);
	}
	catch(e) {
		alert(e.message);
	}
	return(null);
}


/**
 * 条件预加载的方法
 * 实现不用每次调用createXMLHttpRequest函数的时候都判断一下浏览器是IE7+还是IE6
 */
/*
var createXMLHttpRequest = window.XMLHttpRequest?
	function(){
		// code for IE7+, Firefox, Chrome, Opera, Safar
		return new XMLHttpRequest();
	}:
	function(){
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	};
*/


/**
 * 延迟加载方法
 * 实现不用每次调用createXMLHttpRequest函数的时候都判断一下浏览器是IE7+还是IE6
 */
function createXMLHttpRequest() {
	if (window.XMLHttpRequest) {
		createXMLHttpRequest = function() {
			// code for IE7+, Firefox, Chrome, Opera, Safar
			return new XMLHttpRequest();
		};
	} else {
		createXMLHttpRequest = function() {
			// code for IE6, IE5
			return new ActiveXObject("Microsoft.XMLHTTP");
		};
	}
	return createXMLHttpRequest();
}


/**
 * 封装达夫循环
 */
function duffLoop(process,items) {
	var length = items.length;
	var i = length % 8;
	var j = 0;
	while(i--){
		process(items[j++]);
	}
	i = (length * 0.125)^0;
	while(i--){
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
		process(items[j++]);
	}
}



/***********************************
 * 设定接口参数公用函数
 ************************************/

/**
 * Change the time in A04 interface content
 * the first time is current time plus 5 minutes
 * the second time is first time plus 5 minutes
 * until six time;
 */
var changeTime4A04 = function(interfaces) {
	var date = new Date();
	var interval = 5;
	var timePatt = new RegExp();
	var content = interfaces[0].content;

	for (i = 0; i < 6; i++) {
		date.setMinutes(date.getMinutes() + interval);
		timePatt.compile('T'+i+'(?=\\*)',"g");
		content = content.replace(timePatt,date.HHmm())
	}

	interfaces[0].content = content;
}


/**
 * Change the start_time in A13 interface content
 * start_time=current yyyyMMddHH
 */
var changeStartTime4A13 = function(interfaces) {
	var date = new Date();
	var startTimePatt = new RegExp("\\bstart_time\\=[0-9]{10}");

	var content = null;
	var length = interfaces.length;
	for ( i = 0; i < length; i++ ) {
		content = interfaces[i].content;
		if (startTimePatt.test(interfaces[i].content)) {
			content = content.replace(startTimePatt,"start_time="+date.yyyyMMdd()+checkTime(date.getHours()));
			interfaces[i].content = content;
			break;
		}
	}
};

/**
 * Change the end_time in A13 interface content
 * end_time=current yyyyMMddHH
 */
var changeEndTime4A13 = function(interfaces) {
	var date = new Date();
	var endTimePatt = new RegExp("\\bend_time\\=[0-9]{10}");
	
	content = interfaces[0].content;

	if (endTimePatt.test(content)) {
		content = content.replace(endTimePatt,"end_time="+date.yyyyMMdd()+checkTime(date.getHours())); 
		interfaces[0].content = content;
	}
};


/**
 * Change the trans parameter in A21 infterface.
 */
var changeTrans4A21 = function(interfaces,xmlhttp) {
	var timeout = 1*60*1000;
	var transPatt = new RegExp('\\w*(?="})');
	var trans = transPatt.exec(xmlhttp.responseText);
	transPatt.compile('\\btrans=[a-zA-Z0-9]+');

	if (transPatt.test(interfaces[1].content)) {
		interfaces[1].content = interfaces[1].content.replace(transPatt,"trans="+trans);
	}

	transPatt.compile('error');
	// 如果返回的结果包含error字符串，则设置timeout为0
	if (transPatt.test(xmlhttp.responseText)) {
		timeout = 0;
	}

	return timeout;
};

/**
 * change the track time for A18
 */ 
var changeTrackTime4A18 = function(interfaces) {
	var date = new Date();
	//The interval of the track time,minutes
	var intervals = [0,130,100];
	var timePatt = new RegExp();
	var content = interfaces[0].content;

	for (i = 0; i < 3; i++) {
		date.setMinutes(date.getMinutes() + intervals[i]);
		timePatt.compile('T'+i+'(?=\\*)',"g");
		content = content.replace(timePatt,date.HHmm())
	}

	interfaces[0].content = content;
};


/***********************************
 * 接口init 函数集合
 ************************************/


var initA031 = function(interfaces) {
	// change the start time for A13
	changeStartTime4A13(interfaces);
};

var initA13 = function(interfaces) {
	// change the start time for A13
	changeEndTime4A13(interfaces);
};

var initA04 = function(interfaces) {	
	// change times for A04
	changeTime4A04(interfaces);

	//Change A13 start time
	changeStartTime4A13(interfaces);
};

var initA18 = function(interfaces) {
	// change the track time for A18
	changeTrackTime4A18(interfaces);
};


/***********************************
 * 接口callback 函数集合
 ************************************/

var callbackA01 = function(interfaces,xmlhttp) {
	var timeout = 0;
	var sessionidPatt = new RegExp('\\w*(?="})');
	var sessionid = sessionidPatt.exec(xmlhttp.responseText);
	//如果登陆失败，设置interfaces的长度为0（相当于清空数组）
	if (sessionid == null || sessionid == "") {
		interfaces.length = 0;
		return timeout;
	}
	for (var i = interfaces.length; i--; ) {
		// change session id
		interfaces[i].content = interfaces[i].content.replace(/\bsessionid=[a-zA-Z0-9]*/,"sessionid="+sessionid);
	}
	return timeout;
};

var callbackA031 = function(interfaces,xmlhttp) {
	var timeout = 0;
	var transPatt = new RegExp('[0-9]*(?="})');
	var trans = transPatt.exec(xmlhttp.responseText);
	for (var i = 0; i < interfaces.length; i++) {
		// change trans
		interfaces[i].content = interfaces[i].content.replace(/\btrans=[0-9]+/,"trans="+trans);
	}
	return timeout;
};

var callbackA033 = function(interfaces,xmlhttp) {
	var timeout = 0;

	var timeoutPatt = new RegExp('定位中');
	// 如果返回的结果包含“定位中”字符串，则设置timeout为 2 * 60 *1000
	if (timeoutPatt.test(xmlhttp.responseText)) {
		timeout = 2 * 60 * 1000;
	}
	return timeout;
};

var callbackA06 = function(interfaces,xmlhttp) {
	return changeTrans4A21(interfaces,xmlhttp);
};

var callbackA07 = function(interfaces,xmlhttp) {
	return changeTrans4A21(interfaces,xmlhttp);
};

var callbackA12 = function(interfaces,xmlhttp) {
	var timeout = 0;
	var doc = document;
	var password = doc.getElementById("password").value;
	var content = interfaces[1].content;
	

	var passwordPatt = new RegExp('\\bnew_pwd=[a-zA-Z0-9]*');
	// Change new password in interface content
	if (passwordPatt.test(content)) {
		content = content.replace(passwordPatt,"new_pwd="+password);
	}

	passwordPatt.compile('\\bold_pwd=[a-zA-Z0-9]*');
	// Change old password in interface content
	if (passwordPatt.test(content)) {
		content = content.replace(passwordPatt,"old_pwd=123456tt");
	}

	interfaces[1].content = content;
	
	return timeout;
};

var callbackA16 = function(interfaces,xmlhttp) {
	return changeTrans4A21(interfaces,xmlhttp);
};

var callbackA18 = function(interfaces,xmlhttp) {
	return changeTrans4A21(interfaces,xmlhttp);
};

var callbackA182 = function(interfaces,xmlhttp) {
	return changeTrans4A21(interfaces,xmlhttp);
};

var callbackA19 = function(interfaces,xmlhttp) {
	changeTrans4A21(interfaces,xmlhttp);

	var timeout = 2 * 60 * 1000;
	var timeoutPatt = new RegExp('error');
	// 如果返回的结果包含error字符串，则设置timeout为0
	if (timeoutPatt.test(xmlhttp.responseText)) {
		timeout = 0;
	}	
	
	return timeout;
};

var callbackA20 = function(interfaces,xmlhttp) {
	changeTrans4A21(interfaces,xmlhttp);

	var timeout = 2 * 60 * 1000;
	var timeoutPatt = new RegExp('error');
	// 如果返回的结果包含error字符串，则设置timeout为0
	if (timeoutPatt.test(xmlhttp.responseText)) {
		timeout = 0;
	}	
	
	return timeout;
};


/**
 * 从XML文档读取接口，返回一个接口数组
 */
function readInterfaces(dname) {
	/**
	 * 解析接口部分
	 */
	var xmlDoc = loadXMLDoc(dname);
	var interfacesDoc =  xmlDoc.getElementsByTagName("interface");
	var interfaces = [];

	duffLoop(pushInterfaceToArray,interfacesDoc);

	/**
	 * 创建一个接口，然后将该接口压入数组
	 */
	function pushInterfaceToArray(interfaceXMLNode) {
		var actionCode = interfaceXMLNode.firstChild.firstChild.nodeValue;
		var name = interfaceXMLNode.firstChild.nextSibling.firstChild.nodeValue;
		var content = interfaceXMLNode.firstChild.nextSibling.nextSibling.firstChild.nodeValue;
		var init = null;
		var callback = null;
		var regexp = null;

		var initNodes = interfaceXMLNode.getElementsByTagName("init");
		//判断是否存在init节点
		if (initNodes.length >= 1) {
			init = eval(initNodes[0].firstChild.nodeValue);
		}

		var callbackNodes = interfaceXMLNode.getElementsByTagName("callback");
		//判断是否存在callback节点
		if (callbackNodes.length >= 1) {
			callback = eval(callbackNodes[0].firstChild.nodeValue);
		}

		var regexpNodes = interfaceXMLNode.getElementsByTagName("regexp");
		//判断是否存在callback节点
		if (regexpNodes.length >= 1) {
			regexp = regexpNodes[0].firstChild.nodeValue;
		}
		
		var interface = Interface.createNew(actionCode,name,content,init,callback,regexp);
		interfaces.push(interface);
	}

	return interfaces;
}


function initLogFileName() {
	// Log file name
	logFileNameHTML = document.getElementById("logFileName");
	logFileNameHTML.value = "log-"+date2str(new Date(),"yyyy-MM-dd")+".xml";
}

// Automation initialize parameter
function initParameter(interfaces,requestOption) {
	var doc = document;
	var father_mobile = doc.getElementById("father_mobile").value;
	var child_mobile = doc.getElementById("child_mobile").value;
	var password = doc.getElementById("password").value;

	if (requestOption.url == null || requestOption.url == "") {
		alert("请输入测试网址！");
		return false;
	}

	if(father_mobile == null || father_mobile == "") {
		alert("请输入父卡卡号！");
		return false;
	}

	if(child_mobile == null || child_mobile == "") {
		alert("请输入子卡卡号！");
		return false;
	}

	if(password == null || password == "") {
		alert("请输登录密码！");
		return false;
	}
	
	var isError = doc.getElementById("error").checked;

	if (isError == true)
	{
		
		var content = interfaces[0].content;
		// change father mobile
		content = content.replace(/\bmobile=[0-9]*/,"mobile="+father_mobile);

		// change child mobile
		content = content.replace(/\bchild_mobile=[0-9]*/,"child_mobile="+child_mobile);

		// Change Password
		content = content.replace(/\bpwd=[a-zA-Z0-9]*/,"pwd="+password);
		content = content.replace(/\bold_pwd=[a-zA-Z0-9]*/,"old_pwd="+password);
		interfaces[0].content = content;
	} else {
		for (var i = interfaces.length; i--; ) {
			var content = interfaces[i].content;
			// change father mobile
			content = content.replace(/\bfather_mobile=[0-9]*/,"father_mobile="+father_mobile);
			content = content.replace(/\bmobile=[0-9]*/,"mobile="+father_mobile);

			// change child mobile
			content = content.replace(/\bchild_mobile=[0-9]*/,"child_mobile="+child_mobile);

			// Change Password
			content = content.replace(/\bpwd=[a-zA-Z0-9]*/,"pwd="+password);
			content = content.replace(/\bold_pwd=[a-zA-Z0-9]*/,"old_pwd="+password);
			interfaces[i].content = content;
		}
	}	
	return interfaces;
}


function autoCreateHistory(log) {
	// Create request and response history
	var historyHTML = document.getElementById("history");
		
	var tbody = historyHTML.tBodies[0];

	var row = tbody.insertRow(0);

	row.insertCell(0);
	row.cells[0].innerText = log.actionCode; 		

	row.insertCell(1);
	row.cells[1].innerText = log.actionName; 
	
	row.insertCell(2);
	row.cells[2].innerText = log.requestText; 
	
	row.insertCell(3);
	row.cells[3].innerText = log.responseText;

	row.insertCell(4);
	//row.cells[4].innerText = date2str(requestTime,"HH:mm:ss:SSSS yyyy-MM-dd");
	row.cells[4].innerText = log.requestTime;

	row.insertCell(5);
	row.cells[5].innerText = log.elapsedTime;

	row.insertCell(6);
	row.cells[6].innerText = log.result;

	var rowBackgroundColor = row.style.backgroundColor;

	// 设置相邻行颜色不一样
	if( tbody.rows.length & 1 ) {
		rowBackgroundColor = "#FFFFFF";
	}

	if (log.result == Result.Fail) {
		rowBackgroundColor = "#FFFF00";
	}
	row.style.backgroundColor = rowBackgroundColor;

	row.onclick = function() {
		showSelectedLog(this);
	}
	
	// 设置鼠标入和画出后的背景颜色
	row.onmouseover = function() {
		row.style.backgroundColor = "#f895c2";
	}
	
	row.onmouseout = function() {
		row.style.backgroundColor = rowBackgroundColor;
	}
} 


function saveHistory() {
	var doc = document;
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	var logFileName = doc.getElementById("logFileName").value;
	logFileName = location.pathname.substring(1,location.pathname.lastIndexOf('/')+1) + "Log/" + logFileName;
	var file = fso.CreateTextFile(logFileName, true, true);
	var strLog = ['<?xml version="1.0" encoding="utf-16"?>\r\n<Logs>\r\n'];

	// Create request and response history
	var historyHTML = doc.getElementById("history");

	var tbody = historyHTML.tBodies[0];
	var rows = tbody.rows;
	strLogLength = strLog.length;
	for (var i = 0,length = rows.length; i < length; i++) {
		var row = rows[i];
		strLog[strLogLength++] = '    <log>\r\n';
		strLog[strLogLength++] = '        <actionCode>';
		strLog[strLogLength++] = row.cells[0].innerText;
		strLog[strLogLength++] = '</actionCode>\r\n';
		strLog[strLogLength++] = '        <actionName>';
		strLog[strLogLength++] = row.cells[1].innerText;
		strLog[strLogLength++] = '</actionName>\r\n';
		strLog[strLogLength++] = '        <requestText>';
		strLog[strLogLength++] = row.cells[2].innerText.replace(/&/g,'&amp;');
		strLog[strLogLength++] = '</requestText>\r\n';
		strLog[strLogLength++] = '        <responseText>';
		strLog[strLogLength++] = row.cells[3].innerText;
		strLog[strLogLength++] = '</responseText>\r\n';
		strLog[strLogLength++] = '        <requestTime>';
		strLog[strLogLength++] = row.cells[4].innerText;
		strLog[strLogLength++] = '</requestTime>\r\n';
		strLog[strLogLength++] = '        <elapsedTime>';
		strLog[strLogLength++] = row.cells[5].innerText;
		strLog[strLogLength++] = '</elapsedTime>\r\n';
		strLog[strLogLength++] = '        <result>';
		strLog[strLogLength++] = row.cells[6].innerText;
		strLog[strLogLength++] = '</result>\r\n';
		strLog[strLogLength++] = '    </log>\r\n';
	}
	strLog[strLogLength++] = '</Logs>';
	file.WriteLine(strLog.join(""));
	file.close();
	alert("日志文件保存成功！");
}


/**
 * 从XML文档读取日志
 */
function readLog() {
	// Log file name
	var logFileName = "Log/" + document.getElementById("logFileName").value;
	var xmlDoc = loadXMLDoc(logFileName);

	var logsDoc = xmlDoc.getElementsByTagName("log");
	var log = new Object();

	for (var i = logsDoc.length; i--; ) {
		var ch = logsDoc[i];
		var actionCode = ch.childNodes[0].firstChild.nodeValue;
		var actionName = ch.childNodes[1].firstChild.nodeValue;
		var requestText= ch.childNodes[2].firstChild.nodeValue;
		var responseText= ch.childNodes[3].firstChild.nodeValue;
		var requestTime= ch.childNodes[4].firstChild.nodeValue;
		var elapsedTime= ch.childNodes[5].firstChild.nodeValue;
		var result = ch.childNodes[6].firstChild.nodeValue;

		var log = Log.createNew(actionCode, actionName, requestText, responseText, requestTime, elapsedTime, result);
		autoCreateHistory(log);
	}
}


// 清除日志表内容
function clearLog() {
	var logTableHTML = document.getElementById("history");
	var old_tbody = logTableHTML.tBodies[0];
	var new_tbody = document.createElement('tbody');
	logTableHTML.replaceChild(new_tbody, old_tbody);
}

function checkResult(regExp,content) {
	var result = Result.Pass;
	if(regExp == null) {
		return result;
	}
	var checkPatt = new RegExp(regExp);
	if (!checkPatt.test(content)) {
		result = Result.Fail;
	}
	return result;
}


function automation() {
	var doc = document;

	var type = doc.getElementById("type").value;
	if (type == null || type == "") {
		alert("请输入类型！");
		return false;
	}
	var xmlFileName = "interfaceXML/" + type;
	var interfaces = readInterfaces(xmlFileName);

	var autoXMLHttp = createXMLHttpRequest();

	// testing URL
	var TESTING_URL = doc.getElementById("testingURL").value;
	var METHOD = "POST";
	var CONTENT_TYPE = "application/x-www-form-urlencoded";
	var requestOption = RequestOption.createNew(METHOD,TESTING_URL,CONTENT_TYPE);

	var flag = initParameter(interfaces,requestOption);

	if(flag == false) {
		return;
	}

	var run = function() {
		var timeout = 0;
		if(interfaces.length == 0) {
			return;
		}

		var interface = interfaces[0];

		if(autoXMLHttp != null) {
			if(interface.init != null) {
				interface.init(interfaces);
			}

			Timer.start('interface');
			autoXMLHttp.open(requestOption.method, requestOption.url, true);
			autoXMLHttp.onreadystatechange = function() {   
				var loadingDiv = doc.getElementById("loadingDiv");
				// 插入loading图
				loadingDiv.innerHTML = "<img src='image/loading.gif' />";
				// 显示loading层
				loadingDiv.style.display = "";
				
				if (autoXMLHttp.readyState === 4 && (autoXMLHttp.status === 200 || autoXMLHttp.status === 304)) {
					// 数据处理完毕之后，将loading层再隐藏掉
					loadingDiv.style.display = "none";
					Timer.stop('interface');
					if(interface.callback != null) {
						timeout = interface.callback(interfaces,autoXMLHttp);
					}

					var actionCode = interface.actionCode;
					var actionName = interface.name;
					var requestText = interface.content;
					var responseText = autoXMLHttp.responseText;
					var requestTime = date2str(Timer.getStartTime("interface"),"HH:mm:ss:SSSS yyyy-MM-dd");
					var elapsedTime = Timer.getElapsedTime("interface") + " ms";
					var result = checkResult(interface.regexp,autoXMLHttp.responseText);
					var log = Log.createNew(actionCode, actionName, requestText, 
													responseText, requestTime, elapsedTime, result);

					autoCreateHistory(log);

					//如果队列中还有请求，就接着递归执行executeAjax函数，直到队列为空   
					if (interfaces.length > 0) {   
						//删除队列中的第一个请求   
						interfaces.shift();

						// 在timeout(毫秒)后，进行递归调用
						setTimeout(run,timeout);

						if (timeout > 0) {
							// 显示loading层
							loadingDiv.style.display = "";

							var waitToTime = new Date();
							waitToTime.setMilliseconds(waitToTime.getMilliseconds() + timeout);

							// 显示执行下一个接口的倒计时
							var timer = setInterval(function () {
								var timerCountDown = (waitToTime - new Date()) / 1000;

								if (timerCountDown > 0) {
									// 插入loading图
									loadingDiv.innerHTML = "<img src='image/loading.gif' />" + "\n" + Math.round(timerCountDown)+"s";
									return;
								}

								clearInterval(timer);
							},1000);
						}						
					}
				}
			}
			autoXMLHttp.setRequestHeader("Content-Type", requestOption.contentType);
			autoXMLHttp.send(interface.content || null);
		}
	}
	run();
}


/**
 * Load common info for XML document.
 */
function loadCommonInfoXMLDoc(dname) {
	var xmlDoc = loadXMLDoc(dname);
	var doc = document;


	/**
	 * 解析接口文件名
	 */
	var interfaceXMLsDoc = xmlDoc.getElementsByTagName("interfaceXML");
	var typesHTML = doc.getElementById("types");

	// 清除原有数据
	typesHTML.innerHTML = "";

	var firstItem = "--Type--";
	typesHTML.add(new Option(firstItem,firstItem));	
	for(var i = interfaceXMLsDoc.length; i--; ) {
		var ch = interfaceXMLsDoc[i].firstChild;
		var name = ch.firstChild.nodeValue;
		var fileName = ch.nextSibling.firstChild.nodeValue;

		typesHTML.add(new Option(name,fileName));
	}


	/**
	 * 解析电话号码部分
	 */
	var phonesDoc = xmlDoc.getElementsByTagName("phone");
	var fatherMobilesHTML = doc.getElementById("father_mobiles");
	var childMobilesHTML = doc.getElementById("child_mobiles");

	// 清除原有数据
	fatherMobilesHTML.innerHTML = "";
	childMobilesHTML.innerHTML = "";

	firstItem = "--Father Mobile--";
	fatherMobilesHTML.add(new Option(firstItem,firstItem));	
	firstItem = "--Child Mobile--";
	childMobilesHTML.add(new Option(firstItem,firstItem));
	var phoneDoc = null;
	for(var i = phonesDoc.length; i--; ) {
		phoneDoc =  phonesDoc[i].firstChild.nodeValue;
		fatherMobilesHTML.add(new Option(phoneDoc,phoneDoc));
		childMobilesHTML.add(new Option(phoneDoc,phoneDoc));
	}

	/**
	 * 解析密码部分
	 */
	var passwordsDoc = xmlDoc.getElementsByTagName("password");
	var passwordsHTML = doc.getElementById("passwords");
	
	// 清除原有数据
	passwordsHTML.innerHTML = "";

	firstItem = "--Password--";
	passwordsHTML.add(new Option(firstItem,firstItem));

	var passwordDoc = null;
	for(var i = passwordsDoc.length; i--; ) {
		passwordDoc =  passwordsDoc[i].firstChild.nodeValue;
		passwordsHTML.add(new Option(passwordDoc,passwordDoc));
	}


	/**
	 * 解析网址部分
	 */
	var websitesDoc = xmlDoc.getElementsByTagName("website");
	var website = new Object();
	var websitesHTML = doc.getElementById("websites");
	var testingURLsHTML = doc.getElementById("testingURLs");

	// 清除原有数据
	websitesHTML.innerHTML = "";
	testingURLsHTML.innerHTML = "";

	firstItem = "--URL--";
	testingURLsHTML.add(new Option(firstItem,firstItem));
	var websiteHTML = doc.createDocumentFragment();
	for(var i = websitesDoc.length; i--; ) {
		var ch = websitesDoc[i].firstChild;

		website.name = ch.firstChild.nodeValue;
		website.url = ch.nextSibling.firstChild.nodeValue;

		var lab = doc.createElement("label");
		lab.innerHTML = website.name+":";
		lab.className="label";

		var hyperLink = doc.createElement("a");
		hyperLink.href = website.url;
		hyperLink.innerHTML = website.url;

		websiteHTML.appendChild(lab);
		websiteHTML.appendChild(hyperLink);
		websiteHTML.appendChild(doc.createElement('br'));

		//添加测试URL
		testingURLsHTML.add(new Option(website.name,website.url));

	}
	websitesHTML.appendChild(websiteHTML);
}


/**
 * Load interface info form XML document. 
 */
function loadInterfaceXMLDoc(dname) {
	var xmlDoc = loadXMLDoc(dname);
	var doc = document;

	/**
	 * 解析接口部分
	 */
	var interfacesDoc =  xmlDoc.getElementsByTagName("interface");
	var interfacesHTML = doc.getElementById("interfaces");
	var interfaceHTML = doc.createDocumentFragment();

	// 清除原有数据
	interfacesHTML.innerHTML = "";

	duffLoop(addInterfaceToPage,interfacesDoc);

	function addInterfaceToPage(interfaceXMLNode) {
		var ch = interfaceXMLNode.firstChild;
		var actionCode = ch.firstChild.nodeValue;
		var name = ch.nextSibling.firstChild.nodeValue;
		var content = ch.nextSibling.nextSibling.firstChild.nodeValue;
		var regexp = null;

		var regexpNodes = interfaceXMLNode.getElementsByTagName("regexp");
		//判断是否存在callback节点
		if (regexpNodes.length >= 1) {
			regexp = regexpNodes[0].firstChild.nodeValue;
		}
		var interface = Interface.createNew(actionCode,name,content,null,null,regexp);
		
		var contentInputBox = doc.createElement("input");
		contentInputBox.type = "text";
		contentInputBox.id = interface.actionCode;
		contentInputBox.name = interface.name;
		contentInputBox.value = interface.content;
		contentInputBox.regexp = interface.regexp;
		contentInputBox.className = "textbox"
		

		var lab = doc.createElement("label");
		lab.innerHTML = "<br>"+interface.actionCode+"-"+interface.name+"<br>";
		//lab.id = interface.actionCode;
		lab.name = interface.name;
		lab.className="label";

		var actionSendButton = doc.createElement("button");
		actionSendButton.name = interface.name;
		actionSendButton.innerHTML = interface.actionCode;
		actionSendButton.className="button bigrounded orange";
		actionSendButton.style.width = "80px";
		 
		var setRequestButton = doc.createElement("button");
		setRequestButton.innerHTML = interface.actionCode;
		setRequestButton.className="button bigrounded orange";
		setRequestButton.style.width = "80px";
		
		interfaceHTML.appendChild(lab);		
		interfaceHTML.appendChild(actionSendButton);
		interfaceHTML.appendChild(contentInputBox);
		interfaceHTML.appendChild(setRequestButton);
	}
	interfacesHTML.appendChild(interfaceHTML);

	/**
	 * 事件托管
	 * 1.处理点击左边按钮后，发送一个httpRequest请求
	 * 2.处理点击右边按钮后，设置requestText
	 */
	interfacesHTML.onclick = function(e) {
		// x-browser target
		e = e || window.event;
		var target = e.target || e.srcElement;

		// 如果点击的不是按钮不做任何处理
		if (target.nodeName != 'BUTTON') {
			return;
		}

		var nextSibling = target.nextSibling;
		var previousSibling = target.previousSibling;

		// 如果点击的是左边的按钮，直接发送一个httpRequest请求
		if (nextSibling != null && nextSibling.nodeName == "INPUT") {
			var actionElement = nextSibling;
			var actionCode = actionElement.id;
			var actionName = actionElement.name;
			var actionContent = actionElement.value;
			var regexp = actionElement.regexp;

			if (actionCode != null && actionName != null && actionContent != null) {
				var interface = Interface.createNew(actionCode,actionName,actionContent,null,null,regexp);
				testInterface(interface);
			}
		}
		// 如果点击的是右边的按钮，设置requestText
		else if (previousSibling != null && previousSibling.nodeName == "INPUT") {
			var actionElement = target.previousSibling;
			var actionContent = actionElement.value;
			setRequest(actionContent);
		}
	}
}


/**
 * 加载定位他人接口数据
 */
function loadType() {
	var xmlFileName = "interfaceXML/" + document.getElementById("type").value;
	loadInterfaceXMLDoc(xmlFileName);
}



function changeSession() {
	var doc = document;
	var inputs = doc.getElementsByTagName("input");
	var sessionid = doc.getElementById("sessionid").value;

	for(var i = inputs.length; i--; ) {
		inputs[i].value = inputs[i].value.replace(/\bsessionid=[a-zA-Z0-9]*/,"sessionid="+sessionid);
	}
}

function changeFatherMobile() {
	var doc = document;
	var inputs = doc.getElementsByTagName("input");
	var father_mobile= doc.getElementById("father_mobile").value;

	for(var i = inputs.length; i--; ) {
		inputs[i].value = inputs[i].value.replace(/\bfather_mobile=[0-9]*/,"father_mobile="+father_mobile);
		inputs[i].value = inputs[i].value.replace(/\bmobile=[0-9]*/,"mobile="+father_mobile);
	}
}

function changeChildMobile() {
	var doc = document;
	var inputs = doc.getElementsByTagName("input");
	var child_mobile= doc.getElementById("child_mobile").value;

	for(var i = inputs.length; i--; ) {
		inputs[i].value = inputs[i].value.replace(/\bchild_mobile=[0-9]*/,"child_mobile="+child_mobile);
	}
}

function changePassword() {
	var doc = document;
	var inputs = doc.getElementsByTagName("input");
	var password = doc.getElementById("password").value;

	for(var i = inputs.length; i--; ) {
		inputs[i].value = inputs[i].value.replace(/\bpwd=[a-zA-Z0-9]*/,"pwd="+password);
		inputs[i].value = inputs[i].value.replace(/\bold_pwd=[a-zA-Z0-9]*/,"old_pwd="+password);
	}
}


//设置request textarea
function setRequest(Action) {
	requestHTML.innerHTML = Action;
}

	//设置request textarea
function setResponse(responseText) {
	responseHTML.innerHTML = responseText;
}

function testInterface(interface) {
	setRequest(interface.content);

	// testing URL
	var testingURLHTML = document.getElementById("testingURL");

	Timer.start('manualTesting');
	xmlhttp.open("POST",testingURLHTML.value,true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send(interface.content);

	xmlhttp.onreadystatechange=function() {
		//Clear the content which came back at last time;
		responseHTML.value = "";
		
		var loadingDiv = document.getElementById("loadingDiv");
		// 插入loading图
		loadingDiv.innerHTML = "<img src='image/loading.gif' />";
		// 显示loading层
		loadingDiv.style.display = "";
		
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {				
			Timer.stop('manualTesting');
			// 数据处理完毕之后，将loading层再隐藏掉
			loadingDiv.style.display = "none";

			setResponse(xmlhttp.responseText);

			var actionCode = interface.actionCode;
			var actionName = interface.name;
			var requestText = interface.content;
			var responseText = xmlhttp.responseText;
			var requestTime = date2str(Timer.getStartTime("manualTesting"),"HH:mm:ss:SSSS yyyy-MM-dd");
			var elapsedTime = Timer.getElapsedTime("manualTesting") + " ms";
			var result = checkResult(interface.regexp,xmlhttp.responseText);
			var log = Log.createNew(actionCode, actionName, requestText, 
											responseText, requestTime, elapsedTime, result);
			
			autoCreateHistory(log);
		}
	}
}


function showSelectedLog(logRow) {
	var doc = document;
	var requestHTML = doc.getElementById("request");
	var responseHTML = doc.getElementById("response");
	
	requestHTML.value = logRow.cells[2].innerText;
	responseHTML.value = logRow.cells[3].innerText;
}

// Show websites div
function showWebsites() {
	var websites = document.getElementById("websites");
	websites.style.display = websites.style.display=="none"?"":"none";
}

//发起请求的textarea
var requestHTML = null;
//相应的textarea
var responseHTML = null;

var xmlhttp = null;

function init() {
	initLogFileName();

	var doc = document;

	// Request textarea
	requestHTML = doc.getElementById("request");
	
	// Response textarea
	responseHTML = doc.getElementById("response");
	
	// POST button
	var post = doc.getElementById("post");
	
	// Copy request button
	var copyRequest = doc.getElementById("copyRequest");
	
	// testing URL
	var testingURLHTML = doc.getElementById("testingURL");

	xmlhttp = createXMLHttpRequest();
	loadCommonInfoXMLDoc(commonInfoXMLPath);
	loadInterfaceXMLDoc(manualInterfaceXMLPath);

	copyRequest.onclick = function() {
		copyToClipboard(requestHTML.value);
	};
	
	post.onclick = function() {					
		var patt1 = new RegExp("A[a-zA-Z0-9]*","g");
		var actionCode = patt1.exec(requestHTML.innerText);
		var inputBox = doc.getElementById(actionCode);
		var name = inputBox.name;
		var regexp = inputBox.regexp;
		var content = requestHTML.value;

		var interface = Interface.createNew(actionCode,name,content,null,null,regexp);
		testInterface(interface);
	};
}

init();
